package com.redistest.seckill.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.redistest.seckill.mapper.UserMapper;
import com.redistest.seckill.pojo.User;
import com.redistest.seckill.service.TokenService;
import com.redistest.seckill.utils.JwtTokenUtil;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.annotation.Resource;

@Component
public class UserArgumentResolver implements HandlerMethodArgumentResolver {

    @Resource
    private JwtTokenUtil jwtTokenUtil;

    @Resource
    private TokenService tokenService;
    @Resource
    private UserMapper userMapper;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(User.class) &&
                parameter.hasParameterAnnotation(CurrentUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter,
                                  ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest,
                                  WebDataBinderFactory binderFactory) throws Exception {
        // 从请求头获取Token
        String token = webRequest.getHeader("Authorization");
        if (token == null || !token.startsWith("Bearer ")) {
            return null;
        }

        token = token.substring(7);
        if (!jwtTokenUtil.validateToken(token)) {
            return null;
        }

        // 从Token中获取用户名
        String username = jwtTokenUtil.getUsernameFromToken(token);

        // 验证Redis中的Token是否有效
        if (!tokenService.validateToken(username, token)) {
            return null;
        }

        QueryWrapper<User> q = new QueryWrapper();
        q.eq("nickname",username);
        User user = userMapper.selectOne(q);

        return user;
    }
}